package cn.com.yto56.coresystem.business.msg.web.biz.impl;


import cn.com.yto56.coresystem.business.msg.web.biz.IYtoMsgBiz;
import cn.com.yto56.coresystem.business.msg.web.controller.YtoMsgClientController;
import cn.com.yto56.coresystem.business.msg.web.controller.YtoMsgWebSocketHandler;
import cn.com.yto56.coresystem.common.msg.util.base.StringUtils;
import cn.com.yto56.coresystem.common.msg.util.data.DataTypeChangeTool;
import cn.com.yto56.coresystem.common.msg.util.date.DateHandlerTool;
import cn.com.yto56.coresystem.common.msg.util.domain.AppResult;
import cn.com.yto56.coresystem.common.msg.util.dwr.DWRScriptSessionListener;
import cn.com.yto56.coresystem.common.msg.util.io.AppConfigurationUtil;
import cn.com.yto56.coresystem.msg.client.YtoMsgServiceClient;
import org.apache.log4j.Logger;
import org.directwebremoting.ScriptSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.*;

/**
 * Created by wangrui on 2016/5/3.
 */
@Service
public class YtoMsgBizImpl implements IYtoMsgBiz {
    private static final Logger logger = Logger.getLogger(YtoMsgBizImpl.class);
    @Autowired
    private YtoMsgClientController ytoMsgClientController;
    //SOA消息服务
    private static YtoMsgServiceClient ytoMsgServiceClient;

    static {
        String url = AppConfigurationUtil.getPropertyValue("msg.soa.url");
        String REQUEST_TYPE = AppConfigurationUtil.getPropertyValue("msg.soa.type");
        try {
            ytoMsgServiceClient = new YtoMsgServiceClient(url, REQUEST_TYPE);
        } catch (MalformedURLException e) {
            logger.error("SOA客户端初始化失败", e);
        }
    }


    /**
     * 推送数据
     */
    public void sendMsg() {
        //得到所有ScriptSession
        Collection<ScriptSession> sessions = DWRScriptSessionListener.getScriptSessions();
        logger.info(this.getClass().getSimpleName() + " ScriptSession客户端数量：" + sessions.size());
        //遍历每一个ScriptSession
        for (ScriptSession scriptSession : sessions) {
            String appId = (String) scriptSession.getAttribute("yto_msg_appId");
            String userId = (String) scriptSession.getAttribute("yto_msg_userId");
            if (StringUtils.isNotBlank(appId) && StringUtils.isNotBlank(userId)) {
                //获取信息
                ytoMsgServiceClient.bindAppId(appId);
                AppResult appResult = ytoMsgServiceClient.getCurrentMSG(userId, "");
                String autoMessage = "";
                if (appResult == null || appResult.getResultFlag() && (appResult.getDatas() == null || ((List) appResult.getDatas()).size() <= 0)) {
                    autoMessage = "";
                } else {
                    logger.info(this.getClass().getSimpleName() + "sendMsg is [" + autoMessage + "]");
                    autoMessage = DataTypeChangeTool.beanToJSON(appResult);
                }
                ytoMsgClientController.sendMessageAuto(appId, userId, autoMessage);
            }
        }

        List<WebSocketSession> webSocketSessions = YtoMsgWebSocketHandler.sessions;
        logger.info(this.getClass().getSimpleName() + " webSocket客户端数量：" + webSocketSessions.size());
        //遍历每一个WebSocketSession
        for (WebSocketSession webSocketSession : webSocketSessions) {
            String appId = (String) webSocketSession.getAttributes().get("yto_msg_appId");
            String userId = (String) webSocketSession.getAttributes().get("yto_msg_userId");
            if (StringUtils.isNotBlank(appId) && StringUtils.isNotBlank(userId)) {
                //获取信息
                ytoMsgServiceClient.bindAppId(appId);
                AppResult appResult = ytoMsgServiceClient.getCurrentMSG(userId, "");
                String autoMessage = "";
                if (appResult == null || appResult.getResultFlag() && (appResult.getDatas() == null || ((List) appResult.getDatas()).size() <= 0)) {
                    autoMessage = "";
                } else {
                    autoMessage = DataTypeChangeTool.beanToJSON(appResult);
                }
                if (StringUtils.isNotBlank(autoMessage)) {
                    logger.info(this.getClass().getSimpleName() + "sendMsg is [" + autoMessage + "]");
                    TextMessage returnMessage = new TextMessage(autoMessage);
                    try {
                        synchronized (webSocketSession) {
                            webSocketSession.sendMessage(returnMessage);
                        }

                    } catch (IOException e) {
                        logger.error("发送失败", e);
                    }
                }
            }
        }
    }


    /**
     * 补发客户端未确认消息
     */
    public void reSendMsg() {
        //得到所有ScriptSession
        Collection<ScriptSession> sessions = DWRScriptSessionListener.getScriptSessions();
        //遍历每一个ScriptSession
        for (ScriptSession scriptSession : sessions) {
            String appId = (String) scriptSession.getAttribute("yto_msg_appId");
            String userId = (String) scriptSession.getAttribute("yto_msg_userId");
            if (StringUtils.isNotBlank(appId) && StringUtils.isNotBlank(userId)) {
                //获取信息
                ytoMsgServiceClient.bindAppId(appId);
                AppResult appResult = ytoMsgServiceClient.getReSendMSG(userId, "", DateHandlerTool.getDesDate(new Date(), -1, DateHandlerTool.MINUTE, "yyyy-MM-dd HH:mm:ss"));
                String autoMessage = "";
                if (appResult == null || appResult.getResultFlag() && (appResult.getDatas() == null || ((List) appResult.getDatas()).size() <= 0)) {
                    autoMessage = "";
                } else {
                    autoMessage = DataTypeChangeTool.beanToJSON(appResult);
                }
                if (StringUtils.isNotBlank(autoMessage)) {
                    logger.info(this.getClass().getSimpleName() + " reSendMsg is [" + autoMessage + "]");
                    ytoMsgClientController.sendMessageAuto(appId, userId, autoMessage);
                }
            }
        }

        //遍历每一个WebSocketSession
        List<WebSocketSession> webSocketSessions = YtoMsgWebSocketHandler.sessions;
        for (WebSocketSession webSocketSession : webSocketSessions) {
            String appId = (String) webSocketSession.getAttributes().get("yto_msg_appId");
            String userId = (String) webSocketSession.getAttributes().get("yto_msg_userId");
            if (StringUtils.isNotBlank(appId) && StringUtils.isNotBlank(userId)) {
                //获取信息
                ytoMsgServiceClient.bindAppId(appId);
                AppResult appResult = ytoMsgServiceClient.getReSendMSG(userId, "", DateHandlerTool.getDesDate(new Date(), -1, DateHandlerTool.MINUTE, "yyyy-MM-dd HH:mm:ss"));
                String autoMessage = "";
                if (appResult == null || appResult.getResultFlag() && (appResult.getDatas() == null || ((List) appResult.getDatas()).size() <= 0)) {
                    autoMessage = "";
                } else {
                    autoMessage = DataTypeChangeTool.beanToJSON(appResult);
                }
                if (StringUtils.isNotBlank(autoMessage)) {
                    logger.info(this.getClass().getSimpleName() + " reSendMsg is [" + autoMessage + "]");
                    TextMessage returnMessage = new TextMessage(autoMessage);
                    try {
                        synchronized (webSocketSession) {
                            webSocketSession.sendMessage(returnMessage);
                        }
                    } catch (IOException e) {
                        logger.error("发送失败", e);
                    }
                }
            }
        }
    }

    /**
     * 修改消息状态
     *
     * @param appId
     * @param userId
     * @param msgIds
     * @return
     */
    public AppResult modifyMsgState(String appId, String userId, List msgIds) {
        AppResult result = new AppResult();
        //check AppId
        ytoMsgServiceClient.bindAppId(appId);
//        result = ytoMsgServiceClient.checkUser(userId);
//        if (result.getResultFlag()!=null && result.getResultFlag() && msgIds.size() > 0) {
        if (msgIds.size() > 0) {
            List msgList = new ArrayList();
            for (int i = 0; i < msgIds.size(); i++) {
                Map temp_map = new HashMap();
                temp_map.put("yto_msg_msgList_id", Integer.valueOf((String) msgIds.get(i)));
                msgList.add(temp_map);
            }
            result = ytoMsgServiceClient.updateMsgListState(msgList);
        }
        //修改状态
        return result;
    }

    public AppResult checkUser(String appId, String userId) {
        ytoMsgServiceClient.bindAppId(appId);
        AppResult appResult = ytoMsgServiceClient.checkUser(userId);
        return appResult;
    }
}
